package org.ceteca.explica.core.util;

import java.lang.reflect.Method;

import org.ceteca.explica.core.common.BaseVO;

public class ReflectionUtils {

	public ReflectionUtils() {
		super();
	}

	public static String getClassShortName(Class<?> myClass) {
		String[] shortnames = myClass.getName().split("\\.");
		String shortname = null;
		if (shortnames.length > 0)
			shortname = shortnames[shortnames.length - 1];
		return shortname;
	}

	public static Method getSetter(Class<?> myClass, String fieldName) {
		Method result = null;
		if (fieldName == null)
			return null;
		if (fieldName.length() < 1)
			return null;
		String setterName = "set" + fieldName.substring(0, 1).toUpperCase()
				+ fieldName.substring(1);
		Method[] methods = myClass.getDeclaredMethods();
		for (Method m : methods) {
			if (m.getName().equals(setterName)
					&& m.getParameterTypes().length != 0) {
				result = m;
				return result;
			}
		}
		return result;

	}

	public static Method getGetter(Class<?> myClass, String fieldName) {
		Method result = null;
		if (fieldName == null)
			return null;
		if (fieldName.length() < 1)
			return null;
		String getterName = "get" + fieldName.substring(0, 1).toUpperCase()
				+ fieldName.substring(1);
		Method[] methods = myClass.getDeclaredMethods();

		for (Method m : methods) {
			if (m.getName().equals(getterName)
					&& m.getParameterTypes().length == 0) {
				result = m;
				return result;
			}
		}
		return result;
	}

	
	
	/**Put null value in a field (Using Reflection)
	 * @param b
	 * BaseVO
	 * @param fieldName
	 * Name of the field to cancel
	 * @return
	 * Result of the operation
	 */
	public static OperationResult cancelField(BaseVO b, String fieldName) {
		OperationResult result = new OperationResult();
		if (fieldName != null && !fieldName.isEmpty()) {
			Method setParentField = ReflectionUtils.getSetter(b.getClass(),
					fieldName);
			try {
				setParentField.invoke(b, (Object) null);
			} catch (Exception e) {
				result.addResultMessage(OperationResult.RESULT_ERROR,
						new ResultMessage(OperationResult.RESULT_ERROR, e
								.getCause()));
			}
		}
		return result;
	}
}
